package org.lansir.af.view;

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Calendar;

import org.lansir.af.R;
import org.lansir.af.view.adapter.NumericWheelAdapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;

/**
 * A simple dialog containing an {@link android.widget.DatePicker}.
 */
public class DatePickerWheel extends AlertDialog implements OnClickListener {

    private static final String YEAR = "year";
    private static final String MONTH = "month";
    private static final String DAY = "day";
    
    private final OnDateWheelSetListener mCallBack;
    private final Calendar mCalendar;
    private final java.text.DateFormat mTitleDateFormat;

    private int mInitialYear;
    private int mInitialMonth;
    private int mInitialDay;
    
    private WheelView mWheelMonth ;
    private WheelView mWheelYear;
    private WheelView mWheelDay;

   

    /**
     * @param context The context the dialog is to run in.
     * @param callBack How the parent is notified that the date is set.
     * @param year The initial year of the dialog.
     * @param monthOfYear The initial month of the dialog.
     * @param dayOfMonth The initial day of the dialog.
     */
    public DatePickerWheel(Context context,
    		OnDateWheelSetListener callBack,
            int year,
            int monthOfYear,
            int dayOfMonth) {
        this(context, R.style.NoBgDialog, 
                callBack, year, monthOfYear, dayOfMonth);
    }

    /**
     * @param context The context the dialog is to run in.
     * @param theme the theme to apply to this dialog
     * @param callBack How the parent is notified that the date is set.
     * @param year The initial year of the dialog.
     * @param monthOfYear The initial month of the dialog.
     * @param dayOfMonth The initial day of the dialog.
     */
    public DatePickerWheel(Context context,
            int theme,
            OnDateWheelSetListener callBack,
            int year,
            int monthOfYear,
            int dayOfMonth) {
        super(context, theme);

        mCallBack = callBack;
        mInitialYear = year;
        mInitialMonth = monthOfYear;
        mInitialDay = dayOfMonth;
        
        mTitleDateFormat = java.text.DateFormat.
                                getDateInstance(java.text.DateFormat.FULL);
        mCalendar = Calendar.getInstance();
        updateTitle(mInitialYear, mInitialMonth, mInitialDay);
        
        setButton(context.getText(R.string.date_picker_wheel_set), this);
        setButton2(context.getText(R.string.date_picker_wheel_cancel), (OnClickListener) null);
        setIcon(R.drawable.ic_title_settings);
        
        LayoutInflater inflater = 
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.date_picker, null);
        setView(view);
        
        
        
        mWheelYear = (WheelView) view.findViewById(R.id.year);
        mWheelMonth = (WheelView) view.findViewById(R.id.month);
        mWheelDay = (WheelView) view.findViewById(R.id.day);
        
        OnWheelChangedListener listener = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                updateDays(mWheelYear, mWheelMonth, mWheelDay);
                updateTitle(mWheelYear.getCurrentItem() + mInitialYear, mWheelMonth.getCurrentItem(), mWheelDay.getCurrentItem()+1);
            }
        };
        
        mWheelMonth.setViewAdapter(new DateNumericAdapter(context, 1, 12, mInitialMonth));
        mWheelMonth.setCurrentItem(mInitialMonth);
        mWheelMonth.addChangingListener(listener);
        
        mWheelYear.setViewAdapter(new DateNumericAdapter(context, mInitialYear, mInitialYear + 20, 0));
        mWheelYear.setCurrentItem(mInitialYear);
        mWheelYear.addChangingListener(listener);

        updateDays(mWheelYear, mWheelMonth, mWheelDay);
        mWheelDay.setCurrentItem(mInitialDay-1);
        mWheelDay.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				updateTitle(mWheelYear.getCurrentItem() + mInitialYear, mWheelMonth.getCurrentItem(), mWheelDay.getCurrentItem()+1);
			}        	
        });
//        mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
//        mDatePicker.init(mInitialYear, mInitialMonth, mInitialDay, this);
    }

    @Override
    public void show() {
        super.show();

        /* Sometimes the full month is displayed causing the title
         * to be very long, in those cases ensure it doesn't wrap to
         * 2 lines (as that looks jumpy) and ensure we ellipsize the end.
         */
//        TextView title = (TextView) findViewById(R.id.alertTitle);
//        title.setSingleLine();
//        title.setEllipsize(TruncateAt.END);
    }
    
    public void onClick(DialogInterface dialog, int which) {
        if (mCallBack != null) {
        	mCallBack.onDateWheelChanged(mWheelYear.getCurrentItem()+mInitialYear, mWheelMonth.getCurrentItem(), mWheelDay.getCurrentItem()+1);
//            mDatePicker.clearFocus();
//            mCallBack.onDateSet(mDatePicker, mDatePicker.getYear(), 
//                    mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
        }
    }
    
    public void onDateChanged(DatePicker view, int year,
            int month, int day) {
        updateTitle(year, month, day);
    }
    
    public void updateDate(int year, int monthOfYear, int dayOfMonth) {
        mInitialYear = year;
        mInitialMonth = monthOfYear;
        mInitialDay = dayOfMonth;
        mWheelYear.setCurrentItem(year);
        mWheelMonth.setCurrentItem(monthOfYear);
        mWheelDay.setCurrentItem(dayOfMonth);

    }

    private void updateTitle(int year, int month, int day) {
        mCalendar.set(Calendar.YEAR, year);
        mCalendar.set(Calendar.MONTH, month);
        mCalendar.set(Calendar.DAY_OF_MONTH, day);
        setTitle(mTitleDateFormat.format(mCalendar.getTime()));
    }
    
    @Override
    public Bundle onSaveInstanceState() {
        Bundle state = super.onSaveInstanceState();
        state.putInt(YEAR, mWheelYear.getCurrentItem());
        state.putInt(MONTH, mWheelMonth.getCurrentItem());
        state.putInt(DAY, mWheelDay.getCurrentItem());
        return state;
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        int year = savedInstanceState.getInt(YEAR);
        int month = savedInstanceState.getInt(MONTH);
        int day = savedInstanceState.getInt(DAY);
        mWheelYear.setCurrentItem(year);
        mWheelMonth.setCurrentItem(month);
        mWheelDay.setCurrentItem(day);

        updateTitle(year, month, day);
    }
    
    /**
     * Updates day wheel. Sets max days according to selected month and year
     */
    void updateDays(WheelView year, WheelView month, WheelView day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + year.getCurrentItem());
        calendar.set(Calendar.MONTH, month.getCurrentItem());
        
        int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        day.setViewAdapter(new DateNumericAdapter(getContext(), 1, maxDays, calendar.get(Calendar.DAY_OF_MONTH) - 1));
        int curDay = Math.min(maxDays, day.getCurrentItem() +1);
        day.setCurrentItem(curDay - 1, true);
    }
    
    /**
     * Adapter for numeric wheels. Highlights the current value.
     */
    private class DateNumericAdapter extends NumericWheelAdapter {
        // Index of current item
        int currentItem;
        // Index of item to be highlighted
        int currentValue;
        
        /**
         * Constructor
         */
        public DateNumericAdapter(Context context, int minValue, int maxValue, int current) {
            super(context, minValue, maxValue);
            this.currentValue = current;
            setTextSize(16);
        }
        
        @Override
        protected void configureTextView(TextView view) {
            super.configureTextView(view);
            if (currentItem == currentValue) {
                view.setTextColor(0xFF0000F0);
            }
            view.setTypeface(Typeface.SANS_SERIF);
        }
        
        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            currentItem = index;
            return super.getItem(index, cachedView, parent);
        }
    }
    
    public interface OnDateWheelSetListener{
    	void onDateWheelChanged(int year, int monthOfYear, int dayOfMonth);
    }
}

